import { ElemCommon } from "./ElemCommon";
import { ResManager } from "./ResManager";
import { DataControl } from "./DataControl";
const {ccclass, property} = cc._decorator;

@ccclass
export class hall extends cc.Component {

    _dial_node : cc.Node = null;
    @property(cc.Node)
    run_item : cc.Node = null;
    @property(cc.Node)
    select_node : cc.Node = null;
    @property(cc.Prefab)
    score_item : cc.Node = null;
    @property(cc.Prefab)
    alert : cc.Node = null;

    //旋转之后的结果位置
    run_index : number = 0;
    //选择区水果列表
    dedupe_arr : Array<unknown> = [];

    datacontrol: DataControl = null;

    start () {
        this.datacontrol = DataControl.getInstance();
        //旋转区
        this._dial_node = this.node.getChildByName("dial_node");
        this.initDialSprite();
        //开始按钮
        let click_btn = this.node.getChildByName("begin_btn");
        ElemCommon.getInstance().addButtonClickEvent(click_btn, this.node, "hall", "BeginBtnClick");
        //闪光节点
        this.run_item.active = false;

        this.addSelctSprite();

        this.datacontrol.SelfScore = 100;
        this.showSelfScore();
        this.maskNodeAct(false);
    }
    initDialSprite () {
        //添加旋转区水果
        for(let i = 0; i < this._dial_node.childrenCount; i++){
            let item_name =  this.datacontrol.ConfigData[i];
            let sprite_i = this._dial_node.children[i].getComponent(cc.Sprite);
            let path : string = "fruit_res/"+ item_name +".jpg";
            ResManager.getInstance().getSpriteFrameByPath(path, (_sprite_frame: cc.SpriteFrame)=>{
                sprite_i.spriteFrame = _sprite_frame;
            });
        }
    }
    addSelctSprite(){
        //添加选择区水果
        this.dedupe_arr = this.datacontrol.dedupeConfigData();
        for(let i = 0; i < this.dedupe_arr.length; i++){
            let item_i = this.select_node.getChildByName("item_"+i.toString());
            if(!item_i){
                item_i = cc.instantiate(this.score_item);
                item_i.name = "item_"+i.toString();
                let item_com = item_i.getComponent("ScoreItem");
                item_i.parent = this.select_node;
                let name_str : string = this.dedupe_arr[i].toString();
                item_com.Score =  this.datacontrol.DataBase[name_str].score;
                item_com.Cost =  this.datacontrol.DataBase[name_str].cost;
                item_com.NickName = name_str;
                let name_url : string = "fruit_res/"+ name_str +".jpg";
                item_com.loadInit(name_url);
            }
            item_i.active = true;
        }
    }
    getPrizeNumByName(name: string) : number {
        for(let i = 0; i < this.select_node.childrenCount; i++){
            let child = this.select_node.children[i];
            if(child.active = true){
                let child_com = child.getComponent("ScoreItem");
                let child_nick = child_com.NickName;
                if(child_nick == name){
                    return child_com.Num;
                }
            }
        }
        return -1;
    }
    showSelfScore(){
        let selfscore = this.node.getChildByName("selfScore").getComponent(cc.Label);
        selfscore.string =  this.datacontrol.SelfScore.toString();
    }
    maskNodeAct(isAct : boolean){
        let masknode = this.node.getChildByName("maskNode");
        masknode.active = isAct;
    }
    showAlertTips(tips_str : string, fn ?: Function){
        let alert_node = this.node.getChildByName("alert");
        if(!alert_node){
            alert_node = cc.instantiate(this.alert);
            alert_node.parent = this.node;
        }
        alert_node.getComponent("Alert").showAlert(tips_str, fn);
    }
    //点击事件
    BeginBtnClick ( event_touch: { target: { getComponent: (arg0: typeof cc.Button) => { (): any; new(): any; interactable: boolean; }; }; } ) {
        cc.log("begin click");
        if(this.datacontrol.CostSum === 0){
            this.showAlertTips("您没有选择奖品");
            return;
        }
        this.datacontrol.SelfScore -= this.datacontrol.CostSum;
        if(this.datacontrol.SelfScore < 0){
            this.showAlertTips("您的分数不足");
            this.datacontrol.SelfScore += this.datacontrol.CostSum;
            return;
        }

        this.run_item.active = true;
        event_touch.target.getComponent(cc.Button).interactable = false;

        this.showSelfScore();

        let len : number = this._dial_node.childrenCount;
        let run_num = len * 2 + Math.floor(len * Math.random());
        this.maskNodeAct(true);
        this.runFunc(run_num, event_touch, len);
    }
    //运行动画
    runFunc (run_num: number, event_touch: any, len: number) {
        let self = this;
        if(run_num === 0){
            this.runEndFunc(event_touch);
            return;
        }else {
            setTimeout(()=>{
                self.runFunc(run_num, event_touch, len);
            }, 2000/run_num);
        }
        if(this.run_index >= len){
            this.run_index = 0;
        }
        let w_pos =  self._dial_node.convertToWorldSpaceAR(self._dial_node.children[this.run_index].getPosition());
        let n_pos = self.node.convertToNodeSpaceAR(w_pos);
        self.run_item.setPosition(n_pos);
        this.run_index ++;
        run_num --;
    }
    runEndFunc(event_touch: { target: { getComponent: (arg0: typeof cc.Button) => { (): any; new(): any; interactable: boolean; }; }; }){
        event_touch.target.getComponent(cc.Button).interactable = true;
        let cur_index = this.run_index == 0 ? 0 : this.run_index - 1;
        let cur_data =  this.datacontrol.ConfigData[cur_index];
        let cur_score =  this.datacontrol.DataBase[cur_data].score;
        this.maskNodeAct(false);

        if(this.dedupe_arr.includes(cur_data)){
            let num = this.getPrizeNumByName(cur_data);
            if(num === 0){
                this.showAlertTips("很遗憾,您没有中奖");
            } else {
                let win_score = cur_score * num;
                this.showAlertTips("恭喜您,中奖了!!\n获得"+win_score.toString()+"分", ()=>{
                    this.datacontrol.SelfScore += win_score;
                    this.showSelfScore();
                });
            }
        }else{
            this.showAlertTips("很遗憾,您没有中奖");
        }
    }
}
